package com.njym.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.njym.annotation.PermInfo;
import com.njym.entity.PlatformBusinessRec;
import com.njym.entity.SysPaymentMode;
import com.njym.entity.SysUser;
import com.njym.payment.alipay.service.AliPayService;
import com.njym.payment.wxpay.service.WxService;
import com.njym.service.PlatformBusinessRecService;
import com.njym.service.SysPaymentModeService;
import com.njym.tradeStatusConfig.AliTradeStatus;
import com.njym.tradeStatusConfig.WxTradeStatus;
import com.njym.util.PageUtils;
import com.njym.util.SNUtil;
import com.njym.vo.Json;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IDEA
 * author:张善兵
 * Date:2018/8/23
 * Time:下午2:14
 */

@PermInfo(value = "交易明细记录接口")
@RestController
@RequiresPermissions("a:sys:pbr")
@RequestMapping("/platformBusinessRec")
public class PlatformBusinessRecController {
    @Autowired
    PlatformBusinessRecService platformBusinessRecService;

    @Autowired
    private SysPaymentModeService sysPaymentModeService;

    @Autowired
    private AliPayService aliPayService;

    @Autowired
    private WxService wxService;

    private String zero = "0";

    private static final Logger log = LoggerFactory.getLogger(PlatformBusinessRecController.class);

    @PermInfo(value = "添加交易明细记录")
    @RequiresPermissions("a:sys:pbr:add")
    @PostMapping("/add")
    public Json addSysOrganization(@RequestBody String body) {
        PlatformBusinessRec platformBusinessRec = JSON.parseObject(body, PlatformBusinessRec.class);
        String oper = "add platformBusinessRec";

        boolean success = platformBusinessRecService.insert(platformBusinessRec);

        return Json.result(oper, success).data("id", platformBusinessRec.getId());
    }

    @PermInfo("删除交易明细记录")
    @RequiresPermissions("a:sys:pbr:delete")
    @DeleteMapping
    public Json delete(@RequestBody String body) {
        String oper = "delete platformBusinessRec";
        log.info("{}, body: {}", oper, body);
        PlatformBusinessRec platformBusinessRec = JSON.parseObject(body, PlatformBusinessRec.class);

        JSONObject jsonObj = JSON.parseObject(body);
        String id = jsonObj.getString("id");
        boolean success = platformBusinessRecService.deleteById(id);

        return Json.result(oper, success).data("id", platformBusinessRec.getId());
    }

    /**
     * @param
     * @return
     * @date:2018/8/31
     * @time:上午11:17
     * @author:zhangshanbing
     * @description:查询交易明细
     */
    @PermInfo("搜索交易明细记录")
    @RequiresPermissions("a:sys:pbr:queryDetail")
    @PostMapping("/queryDetail")
    public Json queryPlatformBusinessRecDetail(@RequestBody String body) {
        String oper = "query platformBusinessRec detail info";
        log.info("{}, body: {}", oper, body);

        JSONObject json = JSON.parseObject(body);
        Subject currentUser = SecurityUtils.getSubject();
        SysUser user = (SysUser)currentUser.getPrincipal();
        String orgId = user.getOrgId();
        if (zero.equals(orgId)) {
            orgId = null;
        }
        String tradeStatus = json.getString("tradeStatus");
        //交易 冲正记录，充值记录， 退款记录查询
        Integer recType = json.getInteger("recType");
        Integer abnormalFlag = json.getInteger("abnormalFlag");

        String modeId = json.getString("modeId");
        String modeName = json.getString("modeName");
        String channelId = json.getString("channelId");
        String channelName = json.getString("channelName");

        String cardNo = json.getString("cardNo");

        String terminalId = json.getString("terminalId");
        String tradeNo = json.getString("tradeNo");
        String outTradeNo = json.getString("outTradeNo");

        Object timeInterval = json.get("timeInterval");
        Date start = null;
        Date end = null;
        if (timeInterval != null && timeInterval.getClass() == JSONArray.class) {
            JSONArray timeIntervalarr = (JSONArray)timeInterval;
            start = timeIntervalarr.getTimestamp(0);
            end = timeIntervalarr.getTimestamp(1);
        }

        Page<PlatformBusinessRec> page = platformBusinessRecService.queryPlatformBusinessRecDetail(PageUtils.getPageParam(json),
            orgId,
            recType,
            abnormalFlag,
            channelId,
            channelName,
            modeName,
            modeId,
            tradeStatus,
            cardNo,
            terminalId,
            tradeNo,
            outTradeNo,
            start,
            end);
        return Json.succ(oper).data("page", page);
    }

    @PermInfo("下载交易明细")
    @RequiresPermissions("a:sys:pbr:downBillDetail")
    @PostMapping("/down")
    public Json downPlatformBusinessRec(@RequestBody String body) {
        String oper = "down platformBusinessRec info";
        log.info("{}, body: {}", oper, body);
        JSONObject json = JSON.parseObject(body);
        Subject currentUser = SecurityUtils.getSubject();
        SysUser user = (SysUser)currentUser.getPrincipal();
        String orgId = user.getOrgId();
        if (zero.equals(orgId)) {
            orgId = null;
        }
        String tradeStatus = json.getString("tradeStatus");
        //交易 冲正记录，充值记录， 退款记录查询
        Integer recType = json.getInteger("recType");
        Integer abnormalFlag = json.getInteger("abnormalFlag");

        String modeId = json.getString("modeId");
        String modeName = json.getString("modeName");
        String channelId = json.getString("channelId");
        String channelName = json.getString("channelName");

        String cardNo = json.getString("cardNo");

        String terminalId = json.getString("terminalId");
        String tradeNo = json.getString("tradeNo");
        String outTradeNo = json.getString("outTradeNo");

        Object timeInterval = json.get("timeInterval");
        Date start = null;
        Date end = null;
        if (timeInterval != null && timeInterval.getClass() == JSONArray.class) {
            JSONArray timeIntervalarr = (JSONArray)timeInterval;
            start = timeIntervalarr.getTimestamp(0);
            end = timeIntervalarr.getTimestamp(1);
        }
        List<PlatformBusinessRec> list = platformBusinessRecService.downPlatformBusinessRecDetail(
            orgId,
            recType,
            abnormalFlag,
            channelId,
            channelName,
            modeName,
            modeId,
            tradeStatus,
            cardNo,
            terminalId,
            tradeNo,
            outTradeNo,
            start,
            end);

        Map<String,Object> map = new HashMap<>(4);
        map.put("list", list);
        map.put("size",list.size());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        map.put("start",sdf.format(start));
        map.put("end",sdf.format(end));
        return Json.succ(oper).data("map", map);
    }
    /**
     * @param
     * @return
     * @date:2018/8/23
     * @time:下午3:36
     * @author:zhangshanbing
     * @description:none
     */
    @PermInfo("搜索交易明细")
    @RequiresPermissions("a:sys:pbr:query")
    @PostMapping("/query")
    public Json queryPlatformBusinessRec(@RequestBody String body) {
        String oper = "query platformBusinessRec info";
        log.info("{}, body: {}", oper, body);

        JSONObject json = JSON.parseObject(body);
        int current = json.getIntValue("current");
        int size = json.getIntValue("size");
        if (current == 0) {
            current = 1;
        }
        if (size == 0) {
            size = 10;
        }
        Wrapper<PlatformBusinessRec> queryParams = new EntityWrapper<>();
        queryParams.eq("deleted", 0);
        queryParams.orderBy("trade_date", true);
        String tradeStatus = json.getString("tradeStatus");
        //交易 冲正记录，充值记录， 退款记录查询
        Integer recType = json.getInteger("recType");
        if (recType == null || 0 == recType) {
            //不加限制条件
        } else if (1 == recType) {
            queryParams.eq("rec_type", 1);
        } else if (2 == recType) {
            queryParams.eq("rec_type", 2);

        } else if (3 == recType) {
            queryParams.eq("rec_type", 3);
        } else {
            //不加限制条件
        }
        Integer abnormalFlag = json.getInteger("abnormalFlag");
        if (abnormalFlag != null && 1 == abnormalFlag) {
            queryParams.eq("abnormal_flag", 1);//交易异常记录查询统计
        }
        if (tradeStatus != null && StringUtils.isNotEmpty(tradeStatus)) {
            queryParams.like("trade_status", tradeStatus);
        }
        String modeId = json.getString("modeId");
        if (modeId != null && StringUtils.isNotEmpty(modeId)) {
            queryParams.like("mode_id", modeId);
        }
        String tmodeName = json.getString("tmodeName");
        if (tmodeName != null && StringUtils.isNotEmpty(tmodeName)) {
            queryParams.like("tmode_name", tmodeName);
        }
        String tchannelName = json.getString("tchannelName");
        if (tchannelName != null && StringUtils.isNotEmpty(tchannelName)) {
            queryParams.like("tmode_name", tchannelName);
        }
        String cardNo = json.getString("cardNo");
        if (cardNo != null && StringUtils.isNotEmpty(cardNo)) {
            queryParams.like("card_no", cardNo);
        }
        String terminalId = json.getString("terminalId");
        if (terminalId != null && StringUtils.isNotEmpty(terminalId)) {
            queryParams.like("terminal_id", terminalId);
        }
        String outTradeNo = json.getString("outTradeNo");
        if (outTradeNo != null && StringUtils.isNotEmpty(outTradeNo)) {
            queryParams.like("out_trade_no", outTradeNo);
        }
        Object timeInterval = json.get("timeInterval");
        if (timeInterval != null && timeInterval.getClass() == JSONArray.class) {
            JSONArray timeIntervalarr = (JSONArray)timeInterval;
            Date start = timeIntervalarr.getTimestamp(0);
            Date end = timeIntervalarr.getTimestamp(1);
            if (start != null && end != null) {
                queryParams.between("trade_date", start, end);
            }

        }
        //支付平台订单号（支付宝微信等第三方支付平台订单号）不能为null，为null则支付没有成功
        queryParams.isNotNull("trade_no");
        queryParams.notLike("trade_no", " ");

        Page<PlatformBusinessRec> page = platformBusinessRecService.selectPage(new Page<>(current, size), queryParams);
        return Json.succ(oper).data("page", page);
    }

    @PermInfo("查询所有交易统计")
    @RequiresPermissions("a:sys:pbr:allStatistical")
    @PostMapping("/allStatistical")
    public Json getPlatformBusinessAllStatistical(@RequestBody String body) {
        String oper = "getPlatformBusinessAllStatistical";
        log.info("{}, body: {}", oper, body);

        JSONObject json = JSON.parseObject(body);
        Subject currentUser = SecurityUtils.getSubject();
        SysUser user = (SysUser)currentUser.getPrincipal();
        String orgId = user.getOrgId();
        if (orgId.equals(zero)) {
            orgId = null;
        }
        String modeId = json.getString("modeId");
        String cardNo = json.getString("cardNo");
        String terminalId = json.getString("terminalId");
        String outTradeNo = json.getString("outTradeNo");

        Object timeInterval = json.get("timeInterval");
        Date start = null;
        Date end = null;
        if (timeInterval != null && timeInterval.getClass() == JSONArray.class) {
            JSONArray timeIntervalarr = (JSONArray)timeInterval;
            start = timeIntervalarr.getTimestamp(0);
            end = timeIntervalarr.getTimestamp(1);
        }
        List<PlatformBusinessRec> platformBusinessRecs = platformBusinessRecService.getPlatformBusinessAllStatistical(orgId, modeId, cardNo, terminalId,outTradeNo, start, end);
        return Json.succ(oper).data("allStatistical", platformBusinessRecs);
    }

    @PermInfo("查询异常统计")
    @RequiresPermissions("a:sys:pbr:abnormalStatistics")
    @PostMapping("/getAbnormalStatistics")
    public Json getAbnormalStatistics(@RequestBody String body) {
        String oper = "getAbnormalStatistics";

        log.info("{}, body: {}", oper, body);

        JSONObject json = JSON.parseObject(body);
        Subject currentUser = SecurityUtils.getSubject();
        SysUser user = (SysUser)currentUser.getPrincipal();
        String orgId = user.getOrgId();
        if (orgId.equals(zero)) {
            orgId = null;
        }
        String modeId = json.getString("modeId");
        String cardNo = json.getString("cardNo");
        String terminalId = json.getString("terminalId");
        String outTradeNo = json.getString("outTradeNo");

        Object timeInterval = json.get("timeInterval");
        Date start = null;
        Date end = null;
        if (timeInterval != null && timeInterval.getClass() == JSONArray.class) {
            JSONArray timeIntervalarr = (JSONArray)timeInterval;
            start = timeIntervalarr.getTimestamp(0);
            end = timeIntervalarr.getTimestamp(1);
        }

        PlatformBusinessRec platformBusinessRec = platformBusinessRecService.getAbnormalStatistics(orgId, modeId, cardNo, terminalId,outTradeNo, start, end);
        return Json.succ(oper).data("abnormalStatistics", platformBusinessRec);

    }

    @PermInfo("交易退款")
    @RequiresPermissions("a:sys:pbr:refund")
    @PostMapping("/refund")
    public Json refund(@RequestBody String body) {
        String oper = "refund";
        log.info("{}, body: {}", oper, body);
        JSONObject json = JSON.parseObject(body);
        Subject currentUser = SecurityUtils.getSubject();
        SysUser user = (SysUser)currentUser.getPrincipal();

        String id = json.getString("id");
        String orgId = json.getString("orgId");
        String modeId = json.getString("modeId");
        String outTradeNo = json.getString("outTradeNo");
        String refundFee = json.getString("refundFee");
        String channelId = json.getString("channelId");
        String refundReason = json.getString("refundReason");

        if (orgId == null || orgId.equals("")) {
            return Json.fail(oper, "orgId不能为空！");
        }
        if (modeId == null || modeId.equals("")) {
            return Json.fail(oper, "modeId不能为空！");
        }
        // (必填) 商户网站订单系统中唯一订单号，64个字符以内，只能包含字母、数字、下划线，
        if (outTradeNo == null || outTradeNo.equals("")) {
            return Json.fail(oper, "outTradeNo不能为空！");
        }
        if (refundFee == null || refundFee.equals("")) {
            return Json.fail(oper, "refundFee不能为空！");
        }
        if (refundReason == null || refundReason.equals("")) {
            refundReason = "长款订单退款处理";
        }
        PlatformBusinessRec platformBusinessRec = platformBusinessRecService.selectById(id);
        SysPaymentMode sysPaymentMode = sysPaymentModeService.selectById(modeId);
        String result = "";
        String outRequestNo = "";
        boolean resultFlag = false;
        if (sysPaymentMode != null) {
            String modeCode = sysPaymentMode.getModeCode();
            switch (modeCode) {
                case "alipay":
                    outRequestNo= SNUtil.createSN3();
                    String flag =  aliPayService.refund(orgId,outTradeNo,refundFee,refundReason,outRequestNo ,channelId,user.getUid(),user.getUname());
                    switch (flag){
                        case AliTradeStatus.TRADE_SUCCESS:
                            result = "退款成功";
                            resultFlag = true;
                            break;
                        case AliTradeStatus.QUERY_FAILURE:
                            result = "退款失败";
                            break;
                        default:
                            break;
                    }
                    break;
                case "wxpay":
                    outRequestNo = SNUtil.createSN3();
                    String wxResult = wxService.refund(orgId, outTradeNo, outRequestNo, refundFee, refundFee, refundReason,user.getUid(),user.getUname(),channelId);
                    if (wxResult.equals(WxTradeStatus.SUCCESS)) {
                        result = "退款成功";
                        resultFlag = true;
                    } else {
                        result = "退款失败";
                    }
                    break;
                default:
                    result = "支付方式不支持";
                    break;
            }
        } else {
            return Json.fail(oper, "支付方式不存在！");
        }
        if (resultFlag) {
            //更新记录
            platformBusinessRec.setOutRequestNo(outRequestNo);
            platformBusinessRec.updateById();
        }
        return Json.succ(oper).data(result);
    }

}
